package com.kedou.app;

import java.util.HashMap;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.gui.RegisterPage;

import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.kedou.application.Myapplication;
import com.kedou.net.PostLogin;
import com.kedou.net.PostLogin.FailCallback;
import com.kedou.net.PostLogin.SuccessCallback;
import com.kedou.util.DebugUtil;
import com.kedou.util.NetworkUtil;
import com.kedou.util.PreferencesUtil;
import com.kedou.util.Util;

/**
 * 登陆界面
 * 
 * @author zhouchao
 * 
 */
public class LoginActivity extends BaseActivity implements OnClickListener,
		OnTouchListener, OnGestureListener {
	/**
	 * 登陆按钮
	 */
	private Button mBtnLogin;
	/**
	 * 忘记密码 Textview
	 */
	private TextView mTvForgetPassword;
	/**
	 * 注册投资人账号Textview
	 */
	private TextView mTvRegistInvestor;
	/**
	 * 注册创业者账号Textview
	 */
	private TextView mTvRegistEntrepreneur;
	/**
	 * 电话号码或者邮箱 Edittext
	 */
	private EditText mEtPhoneorEmail;
	/**
	 * 登陆密码 Edittext
	 */
	private EditText mEtPassword;
	private String mStrPhoneorEmail;
	private String mStrPassword;
	private GestureDetector mGestureDetector;
	private Myapplication mApplication;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		PushManager.startWork(getApplicationContext(),
				PushConstants.LOGIN_TYPE_API_KEY, Config.BAIDU_API_KEY);
		SMSSDK.initSDK(this, "26904bcdd514", "3ce59a723dc99e8cc696007513d3ca83");
		mApplication = new Myapplication();
		setContentView(R.layout.activity_login);
		setTitle(R.string.welcome_to_kedou);
		initViews();
		setListener();
		mGestureDetector = new GestureDetector((OnGestureListener) this);
		RelativeLayout mRl = (RelativeLayout) findViewById(R.id.root);
		mRl.setOnTouchListener(this);
		mRl.setLongClickable(true);
	}

	/**
	 * 初始化布局
	 */
	private void initViews() {
		mBtnLogin = (Button) findViewById(R.id.bt_login);
		mTvForgetPassword = (TextView) findViewById(R.id.tv_forget_password);
		mTvRegistInvestor = (TextView) findViewById(R.id.tv_regist_investor);
		mTvRegistEntrepreneur = (TextView) findViewById(R.id.tv_regist_entrepreneur);
		mEtPhoneorEmail = (EditText) findViewById(R.id.et_email_or_phone);
		mEtPassword = (EditText) findViewById(R.id.et_password);
	}

	/**
	 * 设置监听器
	 */
	private void setListener() {
		mBtnLogin.setOnClickListener(this);
		mTvForgetPassword.setOnClickListener(this);
		mTvRegistInvestor.setOnClickListener(this);
		mTvRegistEntrepreneur.setOnClickListener(this);
	}

	/**
	 * 点击事件处理
	 */
	@Override
	public void onClick(View v) {
		Intent intent = null;
		switch (v.getId()) {
		case R.id.bt_login:
			mStrPhoneorEmail = mEtPhoneorEmail.getText().toString().trim();
			mStrPassword = mEtPassword.getText().toString().trim();
			if (TextUtils.isEmpty(mStrPhoneorEmail)
					|| TextUtils.isEmpty(mStrPassword)) {
				Toast.makeText(this,
						getResources().getString(R.string.username_isnot_null),
						Toast.LENGTH_SHORT).show();
				return;
			}
			if (!Util.isMobilePhone(mStrPhoneorEmail)
					&& !Util.isEmail(mStrPhoneorEmail)) {
				Toast.makeText(this,
						getStringText(R.string.wrong_phone_or_email),
						Toast.LENGTH_SHORT).show();
			} else {
				if (mStrPassword.length() > 6) {
					mProgressDialog.show();
					// TODO 与后台交互 登陆名,密码
					if (NetworkUtil.isNetworkAvailable(this)) {
						new PostLogin(mStrPhoneorEmail, Util.md5(mStrPassword),
								Config.SOURCE,
								Util.getImei(LoginActivity.this),
								new SuccessCallback() {
									@Override
									public void onSuccess(String token,
											String userId, String userLevel,
											String msg) {
										mProgressDialog.dismiss();
										mApplication.setmToken(token);
										DebugUtil.printE("token", token);
										DebugUtil.printE("userId", userId);
										DebugUtil
												.printE("userLevel", userLevel);
										PreferencesUtil.putString(
												LoginActivity.this, "userId",
												userId);
										PreferencesUtil.putString(
												LoginActivity.this, "token",
												token);
										PreferencesUtil.putString(
												LoginActivity.this,
												"userLevel", userLevel);
										if (userId != null && token != null) {
											Toast.makeText(LoginActivity.this,
													"登陆成功", Toast.LENGTH_SHORT)
													.show();
										}
										new Handler().postDelayed(
												new Runnable() {

													@Override
													public void run() {
														Intent intent = new Intent(
																LoginActivity.this,
																CenterActivity.class);
														LoginActivity.this
																.startActivity(intent);
													}
												}, 1000);

									}
								}, new FailCallback() {
									@Override
									public void onFail(String msg) {
										mProgressDialog.dismiss();
										Toast.makeText(LoginActivity.this, msg,
												Toast.LENGTH_SHORT).show();
									}
								}, LoginActivity.this);
					} else {
						mProgressDialog.dismiss();
						Toast.makeText(
								this,
								getResources().getString(
										R.string.check_your_network),
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(LoginActivity.this,
							getResources().getString(R.string.password_length),
							Toast.LENGTH_SHORT).show();
				}
			}

			break;
		case R.id.tv_forget_password:
			RegisterPage registerPage = new RegisterPage();
			registerPage.setRegisterCallback(new EventHandler() {
				public void afterEvent(int event, int result, Object data) {
					// 解析注册结果
					if (result == SMSSDK.RESULT_COMPLETE) {
						@SuppressWarnings("unchecked")
						HashMap<String, Object> phoneMap = (HashMap<String, Object>) data;
						String country = (String) phoneMap.get("country");
						String phone = (String) phoneMap.get("phone");
						System.out.println(phone);
					}
				}
			});
			registerPage.show(LoginActivity.this);
			// intent = new Intent(this, ForgetPasswordActivity.class);
			// this.startActivity(intent);
			break;
		case R.id.tv_regist_investor:
			intent = new Intent(this, RegistInvestorActivity.class);
			this.startActivity(intent);
			break;
		case R.id.tv_regist_entrepreneur:
			intent = new Intent(this, RegistEntrepreneurActivity.class);
			this.startActivity(intent);
			break;
		}
	}

	private int verticalMinDistance = 20;
	private int minVelocity = 0;

	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		if (e1.getX() - e2.getX() > verticalMinDistance
				&& Math.abs(velocityX) > minVelocity) {

			Toast.makeText(this, "向左手势", Toast.LENGTH_SHORT).show();
		} else if (e2.getX() - e1.getX() > verticalMinDistance
				&& Math.abs(velocityX) > minVelocity) {

			Toast.makeText(this, "向右手势", Toast.LENGTH_SHORT).show();
		}
		return false;
	}

	public boolean onTouch(View v, MotionEvent event) {
		return mGestureDetector.onTouchEvent(event);
	}

	@Override
	public boolean onDown(MotionEvent e) {
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {

		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}

}
